"""
@Project:p8项目
@File:user_model.py
@Author:柴奇峰
@Date:18:46
"""
from flask import Blueprint,jsonify,Response
from flask_restful import Api,Resource,reqparse,marshal
from model import db
from model.user_model import User
from model.model_filter import user_fields
from captcha.image import ImageCaptcha
from celerys.sms.smscode import sms_code
from common.uilts.jwt_auth import _generate_token
from common.uilts.jwt_auth import check_token
from qiniu import Auth
import redis
import random
import string


user_bp = Blueprint('user_bp',__name__)
api = Api(user_bp)

class Sms_code(Resource):
    def post(self):
        pargs = reqparse.RequestParser()
        pargs.add_argument('phone')
        args =pargs.parse_args()
        phone = args.get('phone')
        code = random.randint(100000,999999)
        rds = redis.Redis(host='localhost', password=123, db=2, port=6379)
        key = '%s'%phone
        rest = sms_code.delay(phone,code)
        if rest:
            rds.set(key,code,60)
            return jsonify(message='发送验证码成功',code=200,data=code)
        return jsonify(message='验证码发送失败',code=204)



class Register(Resource):
    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('username')
        parse.add_argument('password')
        parse.add_argument('code')
        parse.add_argument('phone')
        args = parse.parse_args()
        username = args.get('username')
        password = args.get('password')
        phone = args.get('phone')
        code = args.get('code')
        if not all([username,password,phone,code]):
            return jsonify(message='信息不完整',code = 204)
        user = User.query.filter_by(uname = username).first()
        if user:
            return jsonify(message='用户已注册',code=204)
        rds = redis.Redis(host='localhost',password=123,db=2,port=6379)
        key = '%s'%phone
        sms = rds.get(key)
        print('获取到的验证码',sms.decode())
        print('前端传的验证码',code)
        if sms.decode() == code:
            user = User(uname=username,mobile=phone,password=password)
            db.session.add(user)
            db.session.commit()
            return jsonify(message='注册成功',code=200)
        return jsonify(message='验证码错误',code=204)




class SmsImage(Resource):
    def get(self, uuid):
        number = string.ascii_letters + string.digits
        img = "".join(random.sample(number, 4))
        print("img", img)

        img_cap = ImageCaptcha()
        img_code_data = img_cap.generate(img)
        print("img_code_data", img_code_data)

        rds = redis.Redis(host='localhost',port=6379,db=3,password=123)

        key = "image_code:%s"%uuid
        print("key",key)
        rds.set(key, img, ex=60)
        rds.close()

        return Response(img_code_data, content_type="image/png")


class Login(Resource):
    def post(self):
        """登录"""
        pars = reqparse.RequestParser()
        pars.add_argument('account')
        pars.add_argument('password')
        pars.add_argument('uuid')
        pars.add_argument('img_code')
        args = pars.parse_args()
        uname = args.get("account")
        password = args.get("password")
        uuid = args.get("uuid")
        img_code = args.get("img_code")

        rds = redis.Redis(host='localhost',port=6379,db=3,password=123)

        key = "image_code:%s"%uuid
        img_code_cap = rds.get(key)
        if not img_code_cap:
            return jsonify(message='验证码已过期', code=500)
        if img_code.lower() != img_code_cap.decode().lower():

            return jsonify(message='验证码错误', code=400)
        # 登录成功,生成token
        try:
            user = User.query.filter_by(uname=uname).first()
            data = {'user': user.uname,'id': user.uid}
            # 登录生成的token中包含刷新token
            token, refresh_token = _generate_token(data, is_refresh=False)
            if token:
                data_ = {'uid': user.uid, 'token': token, 'refresh_token': refresh_token}
                return jsonify(message='登录成功', code=200, data=data_)
        except Exception as e:
            print('获取用户错误', e)
            return jsonify(message='登录失败', code=400)




class QiniuResource(Resource):
    def get(self):
        ak = 'ZJrTu7uZ7usufrezcxuyRvXko-qIVGh-DlMkCTht'
        sk = 'Y5HsOmq9gky9pNzB2Loe3b_m8DnFKsV9T6aQD8ms'
        q = Auth(ak,sk)
        bucket = 'p8shiyanlou'
        token = q.upload_token(bucket)
        print('七牛云token',token)
        return jsonify(msg='ok',token=token)



class Userinfo(Resource):
    def get(self):
        parse = reqparse.RequestParser()
        parse.add_argument('token')
        args = parse.parse_args()
        token = args.get('token')
        try:
            payload = check_token(token[3:])
        except Exception as e:
            print('解码错误',e)
            return jsonify(message='请先登录',code=401)
        uid = payload.get('id')
        print('token解码的用户信息',payload)
        print('uid',uid)
        user = User.query.filter_by(uid=uid).first()
        data = marshal(user,user_fields)
        return jsonify(msg='获取成功',code=200,data=data)


    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('username')
        parse.add_argument('token')
        parse.add_argument('img')
        args = parse.parse_args()
        uname = args.get('username')
        token = args.get('token')
        img = args.get('img')

        try:
            payload = check_token(token[3:])
        except Exception as e:
            print('解码错误',e)
            return jsonify(message='请先登录',code=401)
        uid = payload.get('id')

        User.query.filter_by(uid=uid).update({'uname':uname,'account':img})
        db.session.commit()

        return jsonify(msg='修改成功',code=200)








api.add_resource(Sms_code,'/sms_code')# 验证码
api.add_resource(Register,'/register')# 注册
api.add_resource(SmsImage,'/sms_image/<uuid:uuid>')# 图片验证码
api.add_resource(Login,'/login')# 登录
api.add_resource(QiniuResource,'/uptoken') # 获取七牛云token
api.add_resource(Userinfo,'/user_info')







